<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <!-- Set render engine for 360 browser -->
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- HTML5 shim for IE8 support of HTML5 elements -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <![endif]-->


    <link href="__ADMIN_TMPL__/public/assets/themes/{:cmf_get_admin_style()}/bootstrap.min.css" rel="stylesheet">
    <link href="__STATIC__/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <style>
        form .input-order {
            margin-bottom: 0px;
            padding: 0 2px;
            width: 42px;
            font-size: 12px;
        }

        form .input-order:focus {
            outline: none;
        }

        .table-actions {
            margin-top: 5px;
            margin-bottom: 5px;
            padding: 0px;
        }

        .table-list {
            margin-bottom: 0px;
        }

        .form-required {
            color: red;
        }
        #error > .error {
            color: red;
            margin-left: 20px;
            margin-bottom: 20px;
        }
    </style>
    <php>
        if(function_exists('cmf_version')){
            $cmf_version = cmf_version();
        } else {
            $cmf_version = '5.0.0';
        }
        
        if (strpos($cmf_version '6.') === 0) {
            $_app=app()->http->getName();
        } else {
            $_app=request()->module();
        }
    </php>
    <script type="text/javascript">
        //全局变量
        var GV = {
            ROOT: "__ROOT__/",
            WEB_ROOT: "__WEB_ROOT__/",
            JS_ROOT: "static/js/",
            APP: '{$_app}'/*当前应用名*/
        };
    </script>
    <script src="__ADMIN_TMPL__/public/assets/js/jquery-1.10.2.min.js"></script>
    <script src="__STATIC__/js/wind.js"></script>
    <script src="__ADMIN_TMPL__/public/assets/js/bootstrap.min.js"></script>
    <script>
        var Base64 = {
            _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",
            encode: function (e) {
                var t = "";
                var n, r, i, s, o, u, a;
                var f = 0;
                e     = Base64._utf8_encode(e);
                while (f < e.length) {
                    n = e.charCodeAt(f++);
                    r = e.charCodeAt(f++);
                    i = e.charCodeAt(f++);
                    s = n >> 2;
                    o = (n & 3) << 4 | r >> 4;
                    u = (r & 15) << 2 | i >> 6;
                    a = i & 63;
                    if (isNaN(r)) {
                        u = a = 64
                    } else if (isNaN(i)) {
                        a = 64
                    }
                    t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
                }
                return t
            },
            decode: function (e) {
                var t = "";
                var n, r, i;
                var s, o, u, a;
                var f = 0;
                e     = e.replace(/[^A-Za-z0-9+/=]/g, "");
                while (f < e.length) {
                    s = this._keyStr.indexOf(e.charAt(f++));
                    o = this._keyStr.indexOf(e.charAt(f++));
                    u = this._keyStr.indexOf(e.charAt(f++));
                    a = this._keyStr.indexOf(e.charAt(f++));
                    n = s << 2 | o >> 4;
                    r = (o & 15) << 4 | u >> 2;
                    i = (u & 3) << 6 | a;
                    t = t + String.fromCharCode(n);
                    if (u != 64) {
                        t = t + String.fromCharCode(r)
                    }
                    if (a != 64) {
                        t = t + String.fromCharCode(i)
                    }
                }
                t = Base64._utf8_decode(t);
                return t
            },
            _utf8_encode: function (e) {
                e     = e.replace(/rn/g, "n");
                var t = "";
                for (var n = 0; n < e.length; n++) {
                    var r = e.charCodeAt(n);
                    if (r < 128) {
                        t += String.fromCharCode(r)
                    } else if (r > 127 && r < 2048) {
                        t += String.fromCharCode(r >> 6 | 192);
                        t += String.fromCharCode(r & 63 | 128)
                    } else {
                        t += String.fromCharCode(r >> 12 | 224);
                        t += String.fromCharCode(r >> 6 & 63 | 128);
                        t += String.fromCharCode(r & 63 | 128)
                    }
                }
                return t
            },
            _utf8_decode: function (e) {
                var t = "";
                var n = 0;
                var r = c1 = c2 = 0;
                while (n < e.length) {
                    r = e.charCodeAt(n);
                    if (r < 128) {
                        t += String.fromCharCode(r);
                        n++
                    } else if (r > 191 && r < 224) {
                        c2 = e.charCodeAt(n + 1);
                        t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                        n += 2
                    } else {
                        c2 = e.charCodeAt(n + 1);
                        c3 = e.charCodeAt(n + 2);
                        t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                        n += 3
                    }
                }
                return t
            }
        }
    </script>
    <script>
        Wind.css('artDialog');
        Wind.css('layer');
        $(function () {
            $("[data-toggle='tooltip']").tooltip();
            $("li.dropdown").hover(function () {
                $(this).addClass("open");
            }, function () {
                $(this).removeClass("open");
            });
        });
    </script>
    <if condition="APP_DEBUG">
        <style>
            #think_page_trace_open {
                z-index: 9999;
            }
        </style>
    </if>
    <link rel="stylesheet" type="text/css" href="__ROOT__/static/js/webuploader/webuploader.css">
    <link rel="stylesheet" type="text/css" href="__ROOT__/static/js/webuploader/image-upload/style.css">
    <style>
        .state-complete .progress {
            display: none;
        }

        #uploader .statusBar .progress {
            vertical-align: middle;
            margin-bottom: 0;
        }

        #uploader .statusBar {
            padding: 0 15px;
        }

        #uploader .statusBar .info {
            line-height: 1.2 !important;
            vertical-align: middle;
        }
    </style>
</head>
<body class="body_none">

<div class="wrap " style="padding:5px;">
    <ul class="nav nav-tabs">
        <php>
            $url_params=input('param.');
            $url_params['tab']='local';
        </php>
        <li class=""><a href="{:url('user/Asset/webuploader',$url_params)}">上传文件</a></li>
        <php>
            $url_params['tab']='url';
        </php>
        <li class=""><a href="{:url('user/Asset/webuploader',$url_params)}">网络文件</a></li>
        <li class="active"><a>上传到云存储</a></li>
        <!--<li class=""><a href="#explorer" data-toggle="tab">文件管理</a></li>-->
    </ul>
    <div class="tabbable">
        <div class="tab-content ">
            <div class="tab-pane" id="wrapper">


            </div>
            <div class="tab-pane" id="B"> 请输入网络地址
                <div class="bk3"></div>
                <input type="hidden" id="img_name" value="">
                <input type="text" id="info" name="info[filename]" class="input form-control" value=""
                       style="width:600px;" placeholder="http://">
            </div>
            <div class="tab-pane  active" id="explorer">
                <div id="container">
                    <!--头部，相册选择和格式选择-->
                    <div id="uploader">
                        <div class="queueList">
                            <div id="dndArea" class="placeholder">
                                <div id="filePicker" class="webuploader-container">

                                </div>
                                <p>或将文件拖到这里，单次最多可选{$max_files}个文件</p>
                            </div>
                        </div>
                        <div class="statusBar" style="display: none">
                            <div class="progress">
                                <span class="text">100%</span>
                                <span class="percentage" style="width: 100%;"></span>
                            </div>
                            <div class="info"></div>
                            <div class="btns">

                            </div>
                        </div>
                        <div id="error"></div>
                    </div>
                </div>


            </div>
        </div>
    </div>

</div>

<script src="__ROOT__/static/js/admin.js"></script>
<script type="text/javascript" src="__PLUGIN_TMPL__/static/lib/plupload-2.1.2/js/plupload.full.min.js"></script>
<script type="text/javascript">
    var htmlBtn = '<div id="selectFiles" class="webuploader-pick">点击选择文件</div>';
    var fileshtml = '';
    $("#filePicker").html(htmlBtn)
    var maxFile = {$max_files};
    var multi_selection = (maxFile > 1)
    var filetemp = [];
    var accessid = '';
    var accesskey = '';
    var host = 'https://oss.aliyuncs.com';
    var getConfigUrl = '';
    var getConfigUrl2 = '{:cmf_plugin_url("Oss://Asset/getConfig",["app"=>$_app])}';
    var policyBase64 = '';
    var signature = '';
    var callbackbody = '';
    var filename = '';
    var key = '';
    var expire = 0;
    var g_object_name = '';
    var g_object_name_type = '';
    var now = timestamp = Date.parse(new Date()) / 1000;
    var length_num = 0
    var filetype = '{$filetype}';

    var running = false;
    function generateUUID() {

        var d = new Date().getTime();

        if (window.performance && typeof window.performance.now === "function") {

            d += performance.now(); //use high-precision timer if available

        }

        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {

            var r = (d + Math.random() * 16) % 16 | 0;

            d = Math.floor(d / 16);

            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);

        });

        return uuid;

    }
    function send_request() {
        var xmlhttp = null;
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        if (xmlhttp != null) {
            serverUrl = getConfigUrl
            xmlhttp.open("GET", serverUrl, false);
            xmlhttp.send(null);
            return xmlhttp.responseText
        }
        else {
            alert("Your browser does not support XMLHTTP.");
        }
    };

    function get_signature() {
        //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
        // now = timestamp = Date.parse(new Date()) / 1000;
        // if (expire < now + 3) {
        //     body = send_request()
        //     var obj = eval("(" + body + ")");
        //     host = obj['host']
        //     policyBase64 = obj['policy']
        //     accessid = obj['accessid']
        //     signature = obj['signature']
        //     expire = parseInt(obj['expire'])
        //     callbackbody = obj['callback']
        //     key = obj['dir']
        //     return true;
        // }
        // return false;
        body = send_request()
        var obj = eval("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback']
        key = obj['dir']
    };

    function random_string(len) {
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    function get_suffix(filename) {
        pos = filename.lastIndexOf('.')
        suffix = ''
        if (pos != -1) {
            suffix = filename.substring(pos)
        }
        return suffix;
    }

    function calculate_object_name(filename) {
        suffix = get_suffix(filename)
        g_object_name = key + generateUUID() + suffix
        return ''
    }

    function set_upload_param(up, file, ret) {
        console.log(file,382)
        let filename = file?file.name:''
        getConfigUrl = getConfigUrl2+'?filename='+filename
        get_signature()
        g_object_name = key;
        if (filename != '') {
            console.log(filename,399)
            suffix = get_suffix(filename)
            calculate_object_name(filename)
        }

        new_multipart_params = {
            'key': g_object_name,
            'policy': policyBase64,
            'OSSAccessKeyId': accessid,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
            'callback': callbackbody,
            'signature': signature,
        };

        up.setOption({
            'url': host,
            'multipart_params': new_multipart_params
        });

        up.start();
    }

    function get_selected_files() {
        var files = [];

        var idPre = 'id' + new Date().getTime();

        var number = $(".filelist li").size();
        for (var i = 0; i < number; i++) {
            var file         = new Object();
            var $file        = $(".filelist li").eq(i);
            console.log($file,417)
            file.id          = idPre + i;
            file.filepath    = $file.data("filepath");
            file.preview_url = $file.data("preview_url");//httpUrl+file.filepath;
            file.url         = $file.data("url");
            file.name        = $file.data("name");
            if (file.url == undefined) {
                continue;
            } else {
                files.push(file);
            }

        }

        return files;
    }
    function reSelectFiles(){
        console.log('re click')
        $("#selectFiles").trigger("click");
    }
    var uploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: document.getElementById('selectFiles'),
        multi_selection: multi_selection,
        container: document.getElementById('filePicker'),
        drop_element:document.getElementById('dndArea'),
        flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
        silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
        url: host,
        filters: {
            mime_types: [ //只允许上传图片和zip文件
                { title: "视频图片", extensions: "jpg,gif,png,bmp,mp4,avi,wmv,rm,rmvb,mkv" },
                { title: "附件", extensions: "txt,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar" }
            ],
            max_file_size: '5000mb', //表单直传的 最大只能上传的文件
            prevent_duplicates: true //不允许选取重复文件
        },
        init: {
            PostInit: function () {

                // document.getElementById('ossfile').innerHTML = '';
            },
            FilesAdded: function (uploader, addFiles) {

                var oldLen = uploader.files.length - addFiles.length;
                // 对addFiles分别生成base64编码，用于预览
                if($("#dndArea").attr('class') === 'placeholder'){
                    $("#dndArea").after('<ul class="filelist"></ul>')
                }
                $("#dndArea").attr('class','placeholder element-invisible')
                $.each(addFiles || [], (i, file)=> {

                    if (!file || !/image\//.test(file.type)) {

                        $('.filelist').append('<li class="imgfiles-item " id="view'+file.id+
                            '" data-id="'+file.id+'" data-name="'+file.name+'">'+
                            '<p class="title">'+file.name+'</p>'+
                            '<p class="imgWrap">文件不能预览</p><p class="progress"><span style="display: block"></span></p></li>')
                    } else {

                        //确保文件是图片
                        if (file.type == 'image/gif') {
                            var fr = new mOxie.FileReader();
                            fr.onload = function () {
                                $('.filelist').append('<li class="imgfiles-item " id="view'+file.id+
                                    '" data-id="'+file.id+'" data-name="'+file.name+'">'+
                                    '<p class="title">'+file.name+'</p>'+
                                    '<p class="imgWrap"><img src="'+fr.result
                                    +'"></p><p class="progress"><span style="display: block"></span></p></li>')
                                fr.destroy();
                                fr = null;
                            }
                            fr.readAsDataURL(file.getSource());
                            // document.getElementById('image').src=fr;
                        } else {
                            var pr = new mOxie.Image();
                            pr.onload = ()=> {
                                // console.log(file)
                                pr.downsize(180, 120);//先压缩一下要预览的图片
                                var imgsrc = pr.type == 'image/jpeg' ? pr.getAsDataURL('image/jpeg', 80) : pr.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
                                $('.filelist').append('<li class="imgfiles-item " id="view'+file.id+
                                    '" data-id="'+file.id+'" data-name="'+file.name+'">'+
                                    '<p class="title">'+file.name+'</p>'+
                                    '<p class="imgWrap"><img src="'+imgsrc
                                    +'"></p><p class="progress"><span style="display: block"></span></p></li>')
                                pr.destroy();
                                pr = null;

                            };
                            // console.log(fileshtml,512)
                            pr.load(file.getSource());
                        }
                    }
                    console.log(fileshtml,513)
                    // $("#dndArea").append('<li>'+html+'</li>')
                });
                // console.log('addfile',fileshtml)
                uploader.start()
            },

            BeforeUpload: function (up, file) {
                console.log('BeforeUpload',502)
                set_upload_param(up,file,true)
                $("#view"+file.id).append('')
            },

            UploadProgress: function (up, file) {
                let view = $("#view"+file.id+'>.progress')
                if(file.percent > 0){
                    view.find('span').attr('style','display:block;width:'+file.percent+'%;')

                }
                if(file.percent === 100){
                    setTimeout(()=>{
                        view.find('span').attr('style','display:none;width:0%;')
                        view.attr('style','display:none;')
                    },500)

                }
                console.log('uploadProgress',file.percent,502)
            },

            FileUploaded: (up, file, info) =>{
                console.log('FileUploaded',info,293);
                let data = {}
                try {
                    data = JSON.parse(info.response);
                } catch(e) {
                    data = {
                        code:0,
                        data:info.response,
                        msg:'网络错误'
                    }
                }

                if(data.code === 1){
                    filetemp = {}
                    filetemp = data.data
                    $('#view'+file.id).data('data',file.id)
                    $('#view'+file.id).data('name',filetemp.name)
                    $('#view'+file.id).data('path',filetemp.path)
                    $('#view'+file.id).data('url',filetemp.url)
                    $('#view'+file.id).data('image_url',filetemp.image_url)
                    $('#view'+file.id).data('preview_url',filetemp.preview_url)
                    $('#view'+file.id).data('filepath',filetemp.filepath)
                    $('#view'+file.id).append('<span class="success"></span>')
                } else {
                    let code = $(data.data).find('code').html()
                    console.log(code,565)
                    if(code === 'CallbackFailed'){
                        $("#view"+file.id+'>.progress').after('<p class="error">请检查回调相关配置</p>')
                    } else {
                        $("#view"+file.id+'>.progress').after('<p class="error">上传失败</p>')
                    }

                    up.trigger('Error', {
                        code : code,
                        message : data.data,
                        file : file
                    });
                }
            },
            UploadComplete:function(up, file){
                console.log('uploadComplete',up,569)
                let statusBar = $(".statusBar")
                let statusProgress = statusBar.find('.progress')
                statusBar.attr('style','')
                let queueProgress = up.total
                let totalNum = queueProgress.failed+queueProgress.uploaded
                if(queueProgress.percent > 0){
                    statusProgress.find('.text').html(queueProgress.percent+'%')
                    statusProgress.find('.percentage').attr('style','width:'+queueProgress.percent+'%;')
                }
                if(queueProgress.percent === 100){
                    setTimeout(()=>{
                        statusProgress.attr('style','display:none;')
                    },500)
                }
                let info = '共'+totalNum+'个文件（'+(queueProgress.size/1024).toFixed(2)+'k），已上传'+queueProgress.uploaded+'个'
                if(queueProgress.failed > 0){
                    info += '，失败'+queueProgress.failed+'个'
                }
                $('.statusBar>.info').html(info)

                if(up.total.uploaded < maxFile){
                    $('.statusBar>.btns').html('<div class="webuploader-pick" onclick="reSelectFiles()">继续添加</div>')
                } else {
                    $('.statusBar>.btns').html('')
                }
            },

            Error: function (up, err) {
                console.log(up,err,579)
                let error = $('#error')
                let time = 10000
                if (err.code == -600) {
                    error.append('<div id="err'+err.file.id+'" class="error">'+err.file.name+' 选择的文件太大了</div>')
                }
                else if (err.code == -601) {
                    error.append('<div id="err'+err.file.id+'" class="error">'+err.file.name+' 选择的文件后缀不对</div>')
                }
                else if (err.code == -602) {
                    error.append('<div id="err'+err.file.id+'" class="error">'+err.file.name+' 这个文件重复添加</div>')
                }
                else if (err.code == -700) {
                    error.append('<div id="err'+err.file.id+'" class="error">'+err.file.name+' 这个文件图片格式错误</div>')
                }
                else if (err.code == -702) {
                    error.append('<div id="err'+err.file.id+'" class="error">'+err.file.name+' 这个文件文件太大超过处理极限</div>')
                }
                else if (err.code == -300) {
                    error.append('<div id="err'+err.file.id+'" class="error">'+err.file.name+' 这个文件文件不可读</div>')
                }
                else if (err.code == -500) {
                    error.append('<div id="err'+err.file.id+'" class="error">'+err.file.name+' 初始化错误</div>')
                }
                else {
                    error.append('<div id="err'+err.file.id+'" class="error"><p>'+err.file.name+'</p><p>Error xml:' + err.message+'</p></div>')
                }
                setTimeout(()=>{
                    $('#err'+err.file.id).remove()
                },time)
            }
        }
    });

    uploader.init();

</script>
</body>
</html>
